package com.project.class8_23;

public class WaitTest {
    public static void main(String[] args) {
        TestObj obj = new TestObj();
        new ObjA(obj).start();
        new ObjB(obj).start();
    }
}

class TestObj{
    public boolean isRun = true;
}

class ObjA extends Thread{
    private TestObj obj;
    public ObjA(TestObj obj){
        this.obj = obj;
    }
    public void run(){
        while(true){
            synchronized (obj) {
                if(obj.isRun == true) {
                    System.out.print("A");
                    obj.isRun = false;

                    try {
                        Thread.sleep(200);
                        //唤醒等待线程访问obj对象
                        obj.notify();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                else{
                    try {
                        //当前线程对obj对象等待
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

class ObjB extends Thread{
    private TestObj obj;
    public ObjB(TestObj obj){
        this.obj = obj;
    }
    public void run(){
        while(true){
            synchronized (obj) {
                if(obj.isRun == false) {
                    System.out.print("B");
                    obj.isRun = true;

                    try {
                        Thread.sleep(200);
                        obj.notify();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                else{
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
